{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n\n# Compiling Stable Diffusion model using the `torch.compile` backend\n\nThis interactive script is intended as a sample of the Torch-TensorRT workflow with `torch.compile` on a Stable Diffusion model. A sample output is featured below:\n\n<img src=\"file://tutorials/images/majestic_castle.png\" width=\"512px\" height=\"512px\" scale=\"50 %\" align=\"right\">\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Imports and Model Definition\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "import torch\nimport torch_tensorrt\nfrom diffusers import DiffusionPipeline\n\nmodel_id = \"CompVis/stable-diffusion-v1-4\"\ndevice = \"cuda:0\"\n\n# Instantiate Stable Diffusion Pipeline with FP16 weights\npipe = DiffusionPipeline.from_pretrained(\n    model_id, revision=\"fp16\", torch_dtype=torch.float16\n)\npipe = pipe.to(device)\n\nbackend = \"torch_tensorrt\"\n\n# Optimize the UNet portion with Torch-TensorRT\npipe.unet = torch.compile(\n    pipe.unet,\n    backend=backend,\n    options={\n        \"truncate_long_and_double\": True,\n        \"enabled_precisions\": {torch.float32, torch.float16},\n    },\n    dynamic=False,\n)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Inference\n\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "with torch.no_grad():\n    prompt = \"a majestic castle in the clouds\"\n    image = pipe(prompt).images[0]\n\n    image.save(\"images/majestic_castle.png\")\n    image.show()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.11.14"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}